package com.tianhao.luo.helper;

import java.util.concurrent.*;

/**
 * @author tianhao.luo@hand-china.com
 */
public class CyclicBarrierDemo2 {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), new ThreadPoolExecutor.CallerRunsPolicy());

        final int[] count = {0};
        CyclicBarrier cyclicBarrier = new CyclicBarrier(10,()->{
            System.out.println("结果："+count[0] / 10);
        });
        for (int i = 0; i < 10; i++) {
            threadPoolExecutor.execute(() -> {
                ThreadLocalRandom current = ThreadLocalRandom.current();
                int i1 = current.nextInt(100);
                System.out.println(i1);
                count[0] = i1+ count[0];
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
        threadPoolExecutor.shutdown();
    }
}
